1
|
|
|
module.exports = (input, callback) => { |
2
|
|
|
const mqtt = require('mqtt') |
3
|
|
|
const configuration = require('./configuration') |
4
|
|
|
const validate = require('./validate') |
5
|
|
|
let error = null |
6
|
|
|
let output = null |
7
|
|
|
|
8
|
|
|
validate.sourceConfiguration(input, (validatedInput, thrownError) => { |
9
|
|
|
input = validatedInput |
10
|
|
|
error = thrownError |
11
|
|
|
}) |
12
|
|
|
validate.paramConfiguration(input, (validatedInput, thrownError) => { |
13
|
|
|
input = validatedInput |
14
|
|
|
error = thrownError |
15
|
|
|
}) |
16
|
|
|
|
17
|
|
|
// Send MQTT |
18
|
|
|
if ( !error ) { |
19
|
|
|
let configurationMqtt = configuration.mqtt(input) |
20
|
|
|
let client = mqtt.connect(input.source.url, configurationMqtt) |
21
|
|
|
|
22
|
|
|
client.on('connect', () => { |
23
|
|
|
client.subscribe(input.source.topic, (errorConnection) => { |
24
|
|
|
if ( !errorConnection ) { |
25
|
|
|
client.publish(input.source.topic, input.params.payload, { |
26
|
|
|
qos: input.params.qos, |
27
|
|
|
retain: false |
28
|
|
|
}) |
29
|
|
|
} else { |
30
|
|
|
error = errorConnection |
31
|
|
|
} |
32
|
|
|
}) |
33
|
|
|
}) |
34
|
|
|
|
35
|
|
|
client.on('message', (topic, message) => { |
36
|
|
|
output = { |
37
|
|
|
'version': {'ref': 'output'}, |
38
|
|
|
'metadata': [ |
39
|
|
|
{'name': 'message', 'value': input.params.payload.toString()}, |
40
|
|
|
{'name': 'receivedMessage', 'value': message.toString()}, |
41
|
|
|
{'name': 'qos', 'value': input.params.qos.toString()}, |
42
|
|
|
{'name': 'timestamp', 'value': Date.now().toString()}, |
43
|
|
|
{'name': 'topic', 'value': topic} |
44
|
|
|
] |
45
|
|
|
} |
46
|
|
|
client.end() |
47
|
|
|
}) |
48
|
|
|
callback(error, output) |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|